﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_TiepNhan_CreateBN
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Event for control "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            If Session("UserId") Is Nothing Then
                Response.Redirect("~/Login.aspx")
            End If
            hidCurHuyenId.Value = Session("HuyenId")
            Load2Grid()
            LoadModeFrom()
        End If
    End Sub
    Protected Sub Load2Grid()
        Using _data As New VSEntities
            'Tỉnh
            Dim TinhDiaDiemKD = (From q In _data.Provinces Where q.ParentId = 0 Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlTinhDiaDiemKD
                .DataSource = TinhDiaDiemKD
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'huyen ho khau
            'tinh hien tai theo huyện
            Dim p = (From q In _data.Provinces Where q.Id = hidCurHuyenId.Value Select q).FirstOrDefault
            Dim huyenDiaDiemKD = (From q In _data.Provinces Where q.ParentId = p.ParentId Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlHuyenDiaDiemKD
                .DataSource = huyenDiaDiemKD
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'xa thi tran hien tai
            Dim xaDiaDiemKD = (From q In _data.Provinces Where q.ParentId = hidCurHuyenId.Value Order By q.Title Select q.Id, q.Code, q.Title).ToList
            With ddlXaThiTranDiaDiemKD
                .DataSource = xaDiaDiemKD
                .DataValueField = "Id"
                .DataTextField = "Title"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With

            'dong vi cap giay chung nhan khac
            Dim d = (From q In _data.DeptIdentifies Order By q.Name Select New With {.Id = q.Id, .Name = q.Name}).ToList
            With ddlOthersPaper_NoiCap
                .DataSource = d
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'giấy tờ khác
            Dim CertifiedPaperDict = (From q In _data.CertifiedPaperDicts Order By q.Name Select New With {.Id = q.Id, .Name = q.Name}).ToList
            With ddlOthersPaper
                .DataSource = CertifiedPaperDict
                .DataValueField = "Id"
                .DataTextField = "Name"
                .DataBind()
                .Items.Insert(0, New ListItem("--- Chọn ---", "0"))
            End With
            'thanh phan ho so
            Dim lstThanhPhanHoSo = (From q In _data.ThanhPhanHoSoes Order By q.IsDefault Descending, q.TenHoSo Select q).ToList
            Dim strKey_Name() As String = {"Id", "MaHoSo", "IsDefault"}
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = lstThanhPhanHoSo
                .DataBind()
            End With

        End Using
    End Sub
    Protected Sub LoadModeFrom()
        Using data As New VSEntities
            txtBizName.Text = "HỘ KINH DOANH "
            Dim p = (From q In data.Provinces Where q.Id = hidCurHuyenId.Value Select q).FirstOrDefault
            'load tinh dia diem kinh doanh
            ddlTinhDiaDiemKD.SelectedValue = p.ParentId 'tỉnh của user hiện tại
            hidHuyenDiaDiemKD.Text = p.ParentId 'tỉnh của user hiện tại
            'load huyen dia diem kinh doanh
            ddlHuyenDiaDiemKD.SelectedValue = hidCurHuyenId.Value 'huyen hien tai user quan ly
            hidHuyenDiaDiemKD.Text = hidCurHuyenId.Value
        End Using

    End Sub
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            Dim checkCode = (From q In data.CertifiedHouseholds Where q.Biz_VietName = txtBizName.Text.Trim() And q.ProvinceId = hidCurHuyenId.Value Select q).FirstOrDefault
            If Not checkCode Is Nothing Then
                Excute_Javascript("Alertbox('Tên hộ kinh doanh đã tồn tại trong hệ thống.')", Me.Page, True)
                Exit Sub
            End If

            Dim p As New VSModel.CertifiedHousehold
            Try
                'Thông tin chung
                p.CertifiedStatus = "M" 'cấp mới
                p.CertifiedUp_Time = 0 'cap moi
                p.CertifiedUp_Date = Now 'ngay nhap ho so
                'thong tin ca nhan
                p.Ow_Name = txtOwRepresentative.Text 'Họ tên
                p.Ow_CardID = txtOwCardId.Text 'Số CMND
                'giay to khac
                'p.Ow_Doc_ID = ddlOthersPaper.SelectedValue 'Giấy tờ khác
                'p.Ow_DocCode = txtOtherPaperCode.Text 'Mã số
                'p.Ow_DocDate = StringToDate(txtOthersPaperDateIssue.Text.Trim()) 'Ngày cấp
                'p.Ow_DocOffiCertifiedID = ddlOthersPaper_NoiCap.SelectedValue 'Nơi cấp

                'Thông tin hộ kinh doanh: 
                p.Biz_VietName = txtBizName.Text.Trim() 'Tên hộ kinh doanh
                p.Ow_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Ow_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Ow_Email = txtOw_Email.Text.Trim() 'Email
                p.Ow_WebSite = txtOw_WebSite.Text.Trim() 'Website

                p.Biz_Tel = txtOw_Tel.Text.Trim() 'điện thoai
                p.Biz_Fax = txtOw_Fax.Text.Trim() 'fax
                p.Biz_Email = txtOw_Email.Text.Trim() 'Email
                p.Biz_Website = txtOw_WebSite.Text.Trim() 'Website

                p.Biz_InvestCapital = 0 ' txtBiz_InvestCapital.Text.Trim() 'vốn kinh doanh
                p.VonTaiSan = 0
                p.VonTienMat = 0
                p.Biz_WordsMoney = "" ' txtMoney_string.Text.Trim() 'Tiền viết bằng chữ

                p.Created = Now
                p.Creator = Session("UserName")
                p.StatusId = TinhTrangHoSo.Nhap ' de duyet tai lieu
                p.NguonTao = NguonTao.MotCua

                p.ProvinceId = hidCurHuyenId.Value ' Huyên đang ký kinh doanh

                'luu thong tin bien nhan 

                Dim _HuyenObj = (From q In data.Provinces Where q.Id = hidCurHuyenId.Value Select q).FirstOrDefault
                If Not _HuyenObj Is Nothing Then
                    Dim _SoNgayTraHoSo As Integer
                    If StringToDateTime(Now.ToString("dd/MM/yyyy"), _HuyenObj.GioBienNhan) > Now Then
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo - 1
                    Else
                        _SoNgayTraHoSo = _HuyenObj.SoNgayTraHoSo
                    End If
                    p.NgayTraHoSo = data.uspGetNumDateDelivery(Now.Date, _SoNgayTraHoSo).FirstOrDefault.DeliveryDate
                End If

                data.CertifiedHouseholds.AddObject(p)
                data.SaveChanges()

                Dim strGCN As String = ""
                If Not p.CertifiedCode Is Nothing Then
                    strGCN = p.CertifiedCode
                End If

                p.ParentId = p.CertifiedID ' ho so dang ky lan parentId = CerId
                data.SaveChanges()

                'địa điểm kinh doanh
                Dim kd As New VSModel.CertifiedHouseholdAddress
                kd.CertifiedID = p.CertifiedID
                kd.TypeId = LoaiDiaChi.DiaDiemKinhDoanh
                kd.Adress = txtBiz_HeadOffice.Text.Trim()
                kd.TinhId = ddlTinhDiaDiemKD.SelectedValue
                'khi set = javascript se ko lay dc  phai set vao hidden field
                kd.HuyenId = hidHuyenDiaDiemKD.Text
                kd.XaThiTranId = hidXaThiTranDiaDiemKD.Text
                data.CertifiedHouseholdAddresses.AddObject(kd)
                data.SaveChanges()
                'luu dia diem kinh doanh vao certifiedhousehold
                'lay tien cac truong theo value
                'xa
                Dim jxd = (From q In data.Provinces Where q.Id = hidXaThiTranDiaDiemKD.Text Select q.Title).FirstOrDefault
                'huyen
                Dim jhd = (From q In data.Provinces Where q.Id = hidHuyenDiaDiemKD.Text Select q.Title).FirstOrDefault
                'tinh
                Dim jtd = (From q In data.Provinces Where q.Id = ddlTinhDiaDiemKD.SelectedValue Select q.Title).FirstOrDefault
                p.XaPhuongId = hidXaThiTranDiaDiemKD.Text ' luu XaPhuongId de report

                p.Biz_HeadOffice = txtBiz_HeadOffice.Text.Trim() & ", " & jxd & ", " & jhd & ", " & jtd
                'start ngành nghề


                'start thành phần hồ sơ
                Dim intId As Integer = 0
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        'lay id cua thanh phan ho so
                        intId = grdShow.DataKeys(item.RowIndex)("Id").ToString
                        Dim ThanhPhanHoSo As New CertifiedHouseholdThanhPhanHoSo
                        ThanhPhanHoSo.CertifiedID = p.CertifiedID
                        ThanhPhanHoSo.ThanhPhanHoSoId = intId
                        data.CertifiedHouseholdThanhPhanHoSoes.AddObject(ThanhPhanHoSo)
                        data.SaveChanges()
                    End If
                Next

                'correct lai Province + HuyenId
                Dim _UserId As Integer = Session("UserId")
                Dim _CertifiedId As Integer = p.CertifiedID
                data.uspCertifiedHouseHouseUpdate(_UserId, _CertifiedId)
                Dim strLog As String = "Giay CN:" & strGCN & ", tên hộ: " & p.Biz_VietName & ", nguoi dai dien: " & p.Ow_Name & ", CMND: " & p.Ow_CardID _
                                    & ", địa chỉ kinh doanh: " & p.Biz_HeadOffice & " huyen: " & p.ProvinceId.ToString & "userid: " & _UserId.ToString
                Insert_App_Log("Tạo  Certified in biên nhận:" & strLog & "", Function_Name.CertifiedHousehold, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))


                Excute_Javascript("Alertbox('Thêm mới dữ liệu thành công.');window.location ='../../Page/TiepNhan/Detail.aspx?Certifiedid=" & p.CertifiedID & "';", Me.Page, True)

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/TiepNhan/List.aspx';", Me.Page, True)
            End Try



        End Using
    End Sub

    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
#End Region

    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = e.Row.RowIndex + 1
            If Not grdShow.DataKeys(e.Row.RowIndex)("IsDefault") Is Nothing Then
                Dim chkItem As CheckBox = e.Row.FindControl("chkItem")
                chkItem.Checked = grdShow.DataKeys(e.Row.RowIndex)("IsDefault")
            End If
        End If
    End Sub
End Class
